package com.example.pt.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.text.SimpleDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 消息清理服务
 * 定期清理超过30天的聊天记录
 */
@Service
public class MessageCleanupService {
    
    private static final Logger logger = LoggerFactory.getLogger(MessageCleanupService.class);
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    /**
     * 每天凌晨2点执行清理任务
     * 删除30天前的聊天记录
     */
    @Scheduled(cron = "0 0 2 * * ?")
    @Transactional
    public void cleanupOldMessages() {
        try {
            // 获取当前时间作为日志记录
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = dateFormat.format(new Date());
            
            logger.info("开始清理30天前的聊天记录: {}", currentTime);
            
            // 执行SQL删除30天前的消息
            int deletedCount = jdbcTemplate.update(
                "DELETE FROM private_message WHERE create_time < DATE_SUB(NOW(), INTERVAL 30 DAY)"
            );
            
            logger.info("聊天记录清理完成，共删除 {} 条消息", deletedCount);
        } catch (Exception e) {
            logger.error("清理聊天记录时发生错误: {}", e.getMessage(), e);
        }
    }
} 